package org.rslai.tcedit.web.product;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.validator.InvalidStateException;
import org.hibernate.validator.InvalidValue;
import org.rslai.tcedit.domain.Product;
import org.rslai.tcedit.domain.ProductUser;
import org.rslai.tcedit.domain.Role;
import org.rslai.tcedit.domain.User;
import org.rslai.tcedit.exception.ApplicationException;
import org.rslai.tcedit.util.HttpUtil;
import org.rslai.tcedit.util.SessionUtil;
import org.rslai.tcedit.web.core.AbstractMvcController;

/**
 * 产品用户管理
 * @author rslai
 *
 * @spring.bean name="/product/assignProductUser.jspx"
 */
public class AssignProductUser extends AbstractMvcController {

	@Override
	public Map<String, Object> getModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String method = request.getMethod();
		Map<String, Object> map = new HashMap<String, Object>();
		ProductUser productUser = null;

		String action = HttpUtil.getString(request, "action", "").toLowerCase();
		String id = HttpUtil.getString(request, "id", "").toLowerCase();

		try {
			if (SessionUtil.getCurrentProductID(request).equals("")) {
				throw new ApplicationException("未选择产品，请先选择一个产品。");
			}

			if (action.equals("delete")) { // 删除
				productUser = (ProductUser) this.productUserService.query(ProductUser.class, id);
				productUserService.delete(productUser);
				response.sendRedirect("/product/assignProductUserList.jspx");
				productUser = null;
			}else if (method.equals("GET")) {
				if  (id.isEmpty()) { // 新增（返回空对象） 
					productUser = new ProductUser();
				} else { // 查询
					productUser = (ProductUser) productUserService.query(ProductUser.class, id);
				}
			}else if(method.equals("POST")) {
				if (action.equals("create")) { // 新增
					productUser = new ProductUser();
					productUser.setProduct((Product) productService.query(Product.class, SessionUtil.getCurrentProductID(request)));
					productUser.setUser((User) userService.query(User.class, HttpUtil.getString(request, "userID", "")));
					productUser.setRole((Role) roleService.query(Role.class, HttpUtil.getString(request, "roleID", "")));
					productUserService.create(productUser);
					response.sendRedirect("/product/assignProductUserList.jspx");
				} else if (action.equals("update")) { // 修改
					productUser = (ProductUser) productUserService.query(ProductUser.class, id);
					productUser.setUser((User) userService.query(User.class, HttpUtil.getString(request, "userID", "")));
					productUser.setRole((Role) roleService.query(Role.class, HttpUtil.getString(request, "roleID", "")));
					productUserService.update(productUser);
					response.sendRedirect("/product/assignProductUserList.jspx");
				}
			}
			
			// 添加用户信息
			List<User> userList = userService.query(true);
			for (ProductUser tmp : productUserService.query(SessionUtil.getCurrentProductID(request))) {
				if (productUser == null ) {
					userList.remove(tmp.getUser());
				} else {
					if (!tmp.getUser().equals(productUser.getUser())) {
						userList.remove(tmp.getUser());
					}
				}
			}
			map.put("users", userList);

			map.put("roles", roleService.queryBonding(true)); // 添加产品角色信息
		} catch(Exception e) {
			map.put("error", convertException(e));
		}

		map.put("action", action);
		map.put("productUser", productUser);

		return map;
	}

	@Override
	public String getView(HttpServletRequest request, HttpServletResponse response) {
		return "/product/assignProductUser.htm";
	}

	private String convertException(Exception e) throws Exception {
		if (e instanceof ApplicationException) {
			return e.getMessage();
		} else if (e instanceof InvalidStateException) {
			StringBuffer sb = new StringBuffer(128);
			InvalidValue[] ivs = ((InvalidStateException) e).getInvalidValues();
			for (InvalidValue iv : ivs)
				sb.append(iv.getMessage()).append("<br/>");
			return sb.toString();
		}
		throw e;
	}

}
